package com.amtf.datafile2.core.excel;

import java.math.BigDecimal;
import java.text.Format;

import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellValue;

import com.amtf.datafile2.DataField;
import com.amtf.datafile2.DataFieldDefinition;
import com.amtf.datafile2.core.std.StdDataFieldParser;

public class ExcelDataFieldParser extends StdDataFieldParser {
	private DataFieldDefinition dfdef;
	private Format format;

	public ExcelDataFieldParser(DataFieldDefinition dfdef, Format format) {
		super(dfdef);

		this.format = format;
	}

	public DataField parse(String value) {
		DataField df = dfdef.newDataFieldInstance();
		df.setValue(value);
		return df;
	}

	public DataField parse(Object value) {
		DataField df = dfdef.newDataFieldInstance();
		if (value instanceof Cell) {
			df.setValue(toValue((Cell) value));
		} else if (value instanceof CellValue) {
			df.setValue(toValue((CellValue) value));
		}

		return df;
	}

	// private static String toValue(Cell cell, FormulaEvaluator evaluator, DataFieldFormat format) {
	private String toValue(Cell cell) {
		if (cell == null) {
			return null;
		}

		switch (cell.getCellType()) {
		case Cell.CELL_TYPE_NUMERIC:
			if (HSSFDateUtil.isCellDateFormatted(cell)) { // 判断是日期类型
				if (format != null) {
					return format.format(cell.getDateCellValue());
				} else {
					return String.valueOf(cell.getDateCellValue());
				}
			} else {
				if (format != null) {
					return format.format(cell.getNumericCellValue());
				} else {
					return new BigDecimal(cell.getNumericCellValue()).toPlainString();
				}
			}
		case Cell.CELL_TYPE_STRING:
			return cell.getStringCellValue();
		case Cell.CELL_TYPE_BLANK:
			return null;
		case Cell.CELL_TYPE_BOOLEAN:
			return String.valueOf(cell.getBooleanCellValue());
		}

		return cell.toString();
	}

	private String toValue(CellValue cellValue) {
		if (cellValue == null) {
			return null;
		}

		switch (cellValue.getCellType()) {
		case Cell.CELL_TYPE_NUMERIC:
			return new BigDecimal(cellValue.getNumberValue()).toPlainString();
		case Cell.CELL_TYPE_STRING:
			return cellValue.getStringValue();
		case Cell.CELL_TYPE_BOOLEAN:
			return String.valueOf(cellValue.getBooleanValue());
		case Cell.CELL_TYPE_BLANK:
			return null;
		}

		return cellValue.toString();
	}

}
